var express = require('express');
var router = express.Router();

var auth = require('../modules/auth');


/**
 * restler is an HTTP client library for node.js.
 * Hides most of the complexity of creating and using http.Client.
 */
var rest = require('restler');

/**
 * 对于所有以/rest/开头的请求，将其原封不动地转发给后端的tomcat服务器
 */
var configREST = {
	url: 'http://192.168.0.21:8080/test'
};

router.route(/^\//)

// 当发现用户未登录时，不将控制权转交给后面的路由，而是让用户登录
.all(auth.requiredAuthentication, function(req, res, next) {
	// runs for all HTTP verbs first
	// think of it as route specific middleware!
	next();
})
.get(function(req, res, next) {
	// 要请求的rest服务器的URI
	var remoteURL = configREST.url + req.url;
	rest.get(remoteURL)
	.on('complete', function(msg) {
		if (msg instanceof Error || msg.error) {
    		res.send({
    			error: true,
    			description: 'Server error. Please try again'
    		});
    		console.log(msg);
    	}else{
			res.send(msg);
    	}
	});
})
.post(function(req, res, next) {
	var remoteURL = configREST.url + req.url;
 	var body = req.body;
 	rest.post(remoteURL, {
		data: body
	})
	.on('complete', function(msg) {
		if (msg instanceof Error || msg.error) {
    		res.send({
    			error: true,
    			description: 'Server error. Please try again'
    		});
    	}else{
			res.send(msg);
    	}
	});
})
.put(function(req, res, next) {
 	var remoteURL = configREST.url + req.url;
 	var body = req.body;

	rest.put(remoteURL, {
		data: body
	})
	.on('complete', function(msg) {
		if (msg instanceof Error || msg.error) {
    		res.send({
    			error: true,
    			description: 'Server error. Please try again'
    		});
    	}else{
			res.send(msg);
    	}
	});
})
.delete(function(req, res, next) {
	var remoteURL = configREST.url + req.url;
	rest.del(remoteURL).on('complete', function(msg) {
		if (msg instanceof Error || msg.error) {
    		res.send({
    			error: true,
    			description: 'Server error. Please try again'
    		});
    	}else{
			res.send(msg);
    	}
	});
})

module.exports = router;
